<template>
  <div>
    <yt-crud
      v-bind="options"
      ref="crudRef"
      @onLoad="getData"
      :fun-props="{
        exportBtn: false,
        delBtn: false,

      }"
      :table-props="{
        selection: false,
        delBtn: true,
        viewBtn: false,
        editBtn: true,
        menuSlot: true,
        menuWidth: 300,
      }"
      :loading="state.loading"
      :total="state.total"
      v-model:page="state.page"
      v-model:query="state.query"
      @delFun="handleDelete"
      @saveFun="onSave"
      @openBeforeFun="openBeforeFun"
      @change="onChange"
    >
      <template #rightToolbar></template>
      <template #menuSlot></template>
      <template #priceId="scope:any">
        {{scope.row.price ? scope.row.price.name : '-'}}
      </template>

      <template #tags="scope:any">
        <template v-if="scope.row.tags">
          <ElTag v-for="(tag, index) in scope.row.tags.split(',')" :key="index">{{tag}}</ElTag>
        </template>
      </template>

      <template #status="scope:any">
        <el-switch v-model="scope.row.status" active-value="Enabled" inactive-value="Disabled" @change="handleStatusChange(scope.row)" />
      </template>

      <template #menuIdsFormItem>
        <el-form-item :label="t('system.role.menuIds')">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>

          <el-tree
            class="tree-border"
            :data="menuOptions"
            :default-expanded-keys="expandedKeys"
            :default-checked-keys="menuIds"
            show-checkbox
            ref="menuTreeRef"
            node-key="id"
            :check-strictly="false"
            empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }"
          />
        </el-form-item>
      </template>
    </yt-crud>
  </div>
</template>

<script lang="ts" setup>
import { IColumn } from '@/components/common/types/tableCommon'
import { saveRole, changeStatus, delRole, listRole } from '@/api/system/role'
import YtCrud from '@/components/common/yt-crud.vue'
import {ComponentInternalInstance} from 'vue'
import {useI18n} from 'vue-i18n'
import { platformTreeSelect } from '@/api/system/menu'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { EnableStatusEnum } = toRefs<any>(proxy?.useEnum('enable_status_enum'))
const { t } = useI18n()

const menuExpand = ref(false)
const menuNodeAll = ref(false)
const menuOptions = ref<any[]>([])
const menuTreeRef = ref<any>({})
const menuIds = ref<any[]>([])
const expandedKeys = ref<any[]>([])

const state = reactive({
  page: {
    pageSize: 12,
    pageNum: 1,
  },
  total: 0,
  loading: false,
  query: {},
})

// 字典
const column = ref<IColumn[]>([
  {
    label: t('system.role.roleName'),
    key: 'roleName',
    search: true,
    formHide: false,
    searchLabelWidth: 120,
    colSpan: 22,
    rules: [{ required: true, message: t('system.role.validator.roleName') }],
  },
  {
    label: t('system.role.roleKey'),
    key: 'roleKey',
    hide: false,
    formHide: false,
    editDisabled: true,
    rules: [{ required: true, message: t('system.role.validator.roleKey') }],
  },
  {
    label: t('system.role.roleSort'),
    key: 'roleSort',
    type: 'number',
    hide: true,
    formHide: false,
    componentProps: {
      style: 'width:200px',
    },
  },
  {
    label: t('system.role.menuIds'),
    key: 'menuIds',
    type: 'string',
    hide: true,
    search: false,
    formHide: false,
    formItemSlot: true,
    editHide: false,
    colSpan: 22,
  },
  {
    label: t('system.role.status'),
    key: 'status',
    type: 'select',
    componentProps: {
      options: EnableStatusEnum,
    },
    search: true,
    formHide: true,
    slot: true,
  },

  {
    label: t('crud.table.column.createTime'),
    key: 'createTime',
    tableWidth: 180,
    sortable: true,
    type: 'date',
    formHide: true,
  },
  {
    label: t('crud.table.column.note'),
    key: 'note',
    hide: true,
    formHide: false,
    colSpan: 22,
    componentProps: {
      type: 'textarea',
      rows: 2,
    }
  },
])
const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  listRole({
    ...state.page,
    ...state.query,
  })
    .then((res: any) => {
      data.value = res.data.rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}


const getDict = () => {

}
getDict()

// 保存数据
const onSave = async ({ data, cancel }: any) => {
  state.loading = true

  data.menuIds = getMenuAllCheckedKeys()
  saveRole(toRaw(data)).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    cancel()
    getData()
  }).finally(()=>{
    state.loading = false
  })
}


/** 查询菜单树结构 */
const getMenuTreeselect = async() => {
  const { data } = await platformTreeSelect()
  menuOptions.value = data

  let checked:any[] = []
  menuOptions.value.forEach((item)=>{
    checked.push(item.id)
  })
  expandedKeys.value = checked
  menuExpand.value = true
}


// 弹窗前置操作
const openBeforeFun = ({data, type}) => {
  getMenuTreeselect()
  if (type === 'add') {
    menuIds.value = []
  } else if (type === 'update') {
    menuIds.value = Object.assign([], data.menuIds)
  }
}

/** 状态修改  */
const handleStatusChange = async (row: any) => {
  if(!row.id)  return
  try {
    await proxy?.$modal.confirm(row.status === 'Enabled' ? t('crud.action.tooltip.enable') : t('crud.action.tooltip.disabled'))
    await changeStatus(row.id, row.status)
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  } catch (err) {
    row.status = row.status === 'Enabled' ? 'Disabled' : 'Enabled'
  }
}

// 删除
const handleDelete = async (row: any) => {
  state.loading = true
  delRole([row.id])
    .then(() => {
      ElMessage.success(t('operate.tooltip.success'))
      getData()
    })
    .finally(() => {
      state.loading = false
    })
}


// 树权限（展开/折叠）
const handleCheckedTreeExpand = (value: any, type: string) => {
  if (type == 'menu') {
    let treeList = menuOptions.value
    for (let i = 0; i < treeList.length; i++) {
      menuTreeRef.value.store.nodesMap[treeList[i].id].expanded = value
    }
  }
}

// 树权限（全选/全不选）
const handleCheckedTreeNodeAll = (value: any, type: string) => {
  if (type == 'menu') {
    menuTreeRef.value.setCheckedNodes(value ? menuOptions.value: [])
  }
}

// 所有菜单节点数据
const getMenuAllCheckedKeys = () => {
  // 目前被选中的菜单节点
  let checkedKeys = menuTreeRef.value.getCheckedKeys()
  // 半选中的菜单节点
  let halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys()
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
  return checkedKeys
}

const multipleSelection = ref<{ deviceId: string }[]>([])

const onChange = (data) => {
  multipleSelection.value = data
}

const options = reactive({
  ref: 'crudRef',
  data,
  column,
})
</script>

<style lang="scss" scoped></style>
